package com.yue.wx.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yue.wx.common.MessageUtil;
import com.yue.wx.common.SignUtil;
import com.yue.wx.service.EventDispatcher;
import com.yue.wx.service.MsgDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhengyl
 * @version date：2019年5月22日 下午2:53:46
 * @description ：
 */
@RestController
public class WxController {

    private static Logger logger = LoggerFactory.getLogger(WxController.class);

    @GetMapping("verify_wx_token")
    public void doGet(HttpServletResponse response,
                      @RequestParam(value = "signature", required = true) String signature,
                      @RequestParam(value = "timestamp", required = true) String timestamp,
                      @RequestParam(value = "nonce", required = true) String nonce,
                      @RequestParam(value = "echostr", required = true) String echostr) {
        try {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                PrintWriter out = response.getWriter();
                out.print(echostr);
                out.close();
            } else {
                logger.info("这里存在非法请求！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @PostMapping("verify_wx_token")
    // post方法用于接收微信服务端消息
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = MessageUtil.parseXml(request);
            String msgtype = map.get("MsgType");
            if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)) {
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                String msgrsp = EventDispatcher.processEvent(map); //进入事件处理
                PrintWriter out = response.getWriter();
                out.print(msgrsp);
                out.close();
            } else {
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                String msgrsp = MsgDispatcher.processMessage(map); //进入消息处理
                PrintWriter out = response.getWriter();
                out.print(msgrsp);
                out.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}